<?php
namespace Zyc\Ceshi;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
//******************************************封装函数*******************************************
class Test{
    /**
     * 将序列化的信息存入到数据库中，进行转换  2017-10-15
     * @param mixed $info 信息    $type 0为序列化，1为反序列化
     */
    public function serializeMysql($info, $type = 0)
    {
        if ($type == 0) {
            return serialize($info);
        } else {
            return unserialize($info);
        }
    }

    /**
     * 把返回的数据集转换成Tree
     * @access public
     * @param array $list 要转换的数据集
     * @param string $pid parent标记字段
     * @param string $level level标记字段
     * @return array
     */
    public function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root == $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }
            }
        }
        return $tree;
    }

    /**
     * ajax成功返回 2017-10-15
     * @param string $data 数据数组 $msg 提示信息   $url 跳转url  $attach 附加数据
     */
    public function ajaxSuccess($data = '', $msg = '操作成功', $url = '', $attach = '')
    {

        $data = array(
            'ret' => 1,
            'data' => $data,
            'msg' => $msg,
        );

        if(!empty($attach)){
            $data['attach'] = $attach;
        }

        return $data;
    }

    /**
     * ajax失败返回 2017-10-15
     * @param string $msg
     */
    public function ajaxFalse($msg = '操作失败', $url = '', $attach = '',$return_data = '')
    {

        $data = array(
            'ret' => 0,
            'msg' => $msg,
            /* 'url' => $url,
             'attach' => $attach*/
        );

        if(!empty($return_data)){
            $data['data'] = $return_data;
        }

        return $data;
    }


    /**
     * ajax失败返回 2017-10-15
     * @param string $msg
     */
    public function ajaxLoginFalse($msg = '请先登陆', $url = '', $attach = '')
    {

        $data = array(
            'ret' => -1,
            'msg' => $msg,
            /* 'url' => $url,
             'attach' => $attach*/
        );

        return $data;
    }

    /**
     * 创建文件夹并赋予777权限 2018-04-16
     * @param string $msg
     */
    function createFile($dir)
    {
        if (substr($dir, -1) == '/') {
            $path = $dir;
        } else {
            $path = dirname($dir);
        }
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
    }

    /**
     * 判断文件是否存在 2018-04-19
     * @param string $msg
     */
    function fileExist($url)
    {
        if (@fopen($url, 'r')) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 随机字符串生成    2017-10-15
     * @param $length 字符串长度
     */
    function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 生成验证码    2017-10-15
     */
    function createverifycode($length = 4)
    {
        $number = "";
        for ($i = 0; $i < $length; $i++) {
            $number .= rand(0, 9);
        }
        return $number;
    }

    /**
     * xml格式转数组    2017-10-15
     */
    function xmltoarray($xml)
    {
//
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);

        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }

    /**
     * 数据XML编码  不含CDATA 2017-10-15
     * @param object $xml XML对象
     * @param mixed $data 数据
     * @param string $item 数字索引时的节点名称
     */
    function dataToXml($xml, $data, $item = 'item')
    {
        foreach ($data as $key => $value) {
            /* 指定默认的数字key */
            is_numeric($key) && $key = $item;

            /* 添加子元素 */
            if (is_array($value) || is_object($value)) {
                $child = $xml->addChild($key);
                $this->dataToXml($child, $value, $item);
            } else {
                $child = $xml->addChild($key, $value);
            }
        }
    }

    /**
     * *号隐藏敏感数字
     * @param $string
     * @param $sublen
     * @param int $start
     * @param string $code
     * @return string
     */
    function cut_str($string, $sublen, $start = 0, $code = 'UTF-8')
    {
        if($code == 'UTF-8')
        {
            $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
            preg_match_all($pa, $string, $t_string);
            if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen));
            return join('', array_slice($t_string[0], $start, $sublen));
        }
        else
        {
            $start = $start*2;
            $sublen = $sublen*2;
            $strlen = strlen($string);
            $tmpstr = '';

            for($i=0; $i< $strlen; $i++)
            {
                if($i>=$start && $i< ($start+$sublen))
                {
                    if(ord(substr($string, $i, 1))>129)
                    {
                        $tmpstr.= substr($string, $i, 2);
                    }
                    else
                    {
                        $tmpstr.= substr($string, $i, 1);
                    }
                }
                if(ord(substr($string, $i, 1))>129) $i++;
            }
            //if(strlen($tmpstr)< $strlen ) $tmpstr.= "...";
            return $tmpstr;
        }
    }

    /**
     * 数组转xml 初始号专用
     * @param $arr
     * @return string
     */
    function arrayToXml($arr) {
        $xml = "<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map>
    <string name=\"deviceInfo\">";
        $xml.= json_encode($arr);
        $xml.="</string></map>";
        return $xml;
    }

    /**
     * 根据经纬度计算距离    2017-10-15
     * @param $lat经度 $lng维度
     */
    function getdistance($lat1, $lng1, $lat2, $lng2)
    {
        $EARTH_RADIUS = 6378.137;
        $radLat1 = $this->rad($lat1);
        $radLat2 = $this->rad($lat2);
        $a = $radLat1 - $radLat2;
        $b = $this->rad($lng1) - $this->rad($lng2);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) +
                cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $EARTH_RADIUS;
        $s = round($s, 3);//千米为单位，3位小数
        return $s;
    }

    /**
     * rad  2017-10-15
     */
    function rad($d)
    {
        return $d * 3.1415926535898 / 180.0;
    }

    /**
     * 转换周几    2017-10-15
     * @param $week 周几数字格式
     */
    function toweek($week)
    {
        switch ($week) {
            case 0:
                return '日';
            case 1:
                return '一';
            case 2:
                return '二';
            case 3:
                return '三';
            case 4:
                return '四';
            case 5:
                return '五';
            case 6:
                return '六';
            default:
                return false;
        }
    }

    /**
     * 时间细分    2017-10-15
     * @param $createtime 时间戳
     * @return int|string
     */
    function time_refine($createtime)
    {
        $time = time() - $createtime;
        $days = intval($time / 86400);
        //计算小时数
        $remain = $time % 86400;
        $hours = intval($remain / 3600);
        //计算分钟数
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        //计算秒数
        $secs = $remain % 60;
        if ($days != 0) {
            $time = $days . '天前';
        } elseif ($hours != 0) {
            $time = $hours . '小时前';
        } elseif ($mins != 0) {
            $time = $mins . '分钟前';
        } else {
            $time = $secs . '秒前';
        }
        return $time;
    }

    /**
     * 时间细分    2017-10-15
     * @param $create_time 时间戳
     * @return int|string
     */
    function time_refine_2($create_time)
    {
        $time = time() - $create_time;
        $days = intval($time / 86400);
        //计算小时数
        $remain = $time % 86400;
        $hours = intval($remain / 3600);
        //计算分钟数
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        //计算秒数
        $secs = $remain % 60;
        if ($days != 0) {
            $time = date('Y-m-d H:i', $create_time);
        } elseif ($hours != 0) {
            $time = $hours . '小时前';
        } elseif ($mins != 0) {
            $time = $mins . '分钟前';
        } else {
            $time = $secs . '秒前';
        }
        return $time;
    }


    /**
     * 时间细分
     * @param $min_time
     * @param $max_time
     * @return string
     */
    function time_refine_3($min_time, $max_time)
    {
        $time = $max_time - $min_time;
        $days = intval($time / 86400);
        //计算小时数
        $remain = $time % 86400;
        $hours = intval($remain / 3600);
        //计算分钟数
        $remain = $remain % 3600;
        $mins = intval($remain / 60);
        //计算秒数
        $secs = $remain % 60;
        if ($days != 0) {
            $time = $days . '天';
        } elseif ($hours != 0) {
            $time = $hours . '小时';
        } elseif ($mins != 0) {
            $time = $mins . '分钟';
        } else {
            $time = $secs . '秒';
        }
        return $time;
    }

    /**
     * 获取当前http协议    2018-04-18
     */
    function getProtocol()
    {
        if (!input('?server.REQUEST_SCHEME')) {
            $protocol = input('server.SERVER_PORT') == 443 ? "https" : "http";
        } else {
            $protocol = input('server.REQUEST_SCHEME');
        }
        return $protocol;
    }

    /**
     * 获取当前全部url    2017-10-15
     */
    function get_url()
    {
        $protocol = getProtocol();
        return $protocol . '://' . input('server.HTTP_HOST') . input('server.REQUEST_URI');
    }

    /**
     * 获取当前的网址加目录信息    2017-10-15
     */
    function getDomain()
    {
        $base = request()->root();
        $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
        if ('' != $root) {
            $root = '/' . ltrim($root, '/');
        }
        if (!input('?server.REQUEST_SCHEME')) {
            $protocol = input('server.SERVER_PORT') == 443 ? "https" : "http";
        } else {
            $protocol = input('server.REQUEST_SCHEME');
        }
        return $protocol . '://' . input('server.HTTP_HOST') . $root;
    }

    /**
     * 获取当前或者服务器端的IP    2018-04-19
     * @param  int $type 获取服务器IP类型 1为本地服务器 2为代码服务器
     */
    function get_client_ip($type = 1)
    {
        if ($type == 1) {
            return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
        } else if ($type == 2) {
            return isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : '0.0.0.0';
        }
    }

    /**
     * 系统非常规MD5加密方法    2017-10-15
     * @param  string $str 要加密的字符串
     */
    function think_ucenter_md5($str, $key = 'ThinkUCenter')
    {
        return '' === $str ? '' : md5(sha1($str) . $key);
    }

    /**
     * 检测手机号    2017-10-15
     */
    function isMobilephone($mobilehone = '')
    {
        if (preg_match("/1[3456789]{1}\d{9}$/", $mobilehone)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检验是否是座机号
     * @param string $seat_number
     * @return bool
     */
    function isSeatNumber($seat_number = '')
    {
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        if (!preg_match($isTel, $seat_number)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检验是否是座机号或是手机号
     * @param string $phone
     * @return bool
     */
    function isPhone($phone = '')
    {
        $isMob = "/^1[3-9]{1}[0-9]{9}$/";
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        if (!preg_match($isMob, $phone) && !preg_match($isTel, $phone)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检测身份证号    2018-03-21
     */
    function isCreditNo($vStr)
    {
        $vCity = array(
            '11', '12', '13', '14', '15', '21', '22',
            '23', '31', '32', '33', '34', '35', '36',
            '37', '41', '42', '43', '44', '45', '46',
            '50', '51', '52', '53', '54', '61', '62',
            '63', '64', '65', '71', '81', '82', '91'
        );
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
        if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);
        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }
        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17; $i >= 0; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
            }
            if ($vSum % 11 != 1) return false;
        }
        return true;
    }


    /**
     * POST请求    2017-10-15
     */
    function httpdata($url, $data, $json_transfer = 1)
    {
        if ($json_transfer == 1) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }else if($json_transfer == 2){
            $data = urldecode(json_encode($data, JSON_UNESCAPED_UNICODE));
        }

        //$data = JSON($data, false);

        $ch = curl_init();
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8'));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $status = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($status, true);
        return $res;
    }

    /**
     * 以post方式提交xml到对应的接口url    2017-10-15
     * @param void $xml xml数据
     * @param string $url 接口url
     * @param int $curl_timeout curl超时时间
     */
    function postXmlCurl($xml, $url, $curl_timeout = 30, $certificate = [])
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);//设置超时
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');//这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //要求结果为字符串且输出到屏幕上


        if (!empty($certificate)) {
            //默认格式为PEM，可以注释
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . $certificate['cert_url']);
            //默认格式为PEM，可以注释
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . $certificate['key_url']);
        }

        curl_setopt($ch, CURLOPT_POST, TRUE);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

    /**
     * GET请求    2017-10-15
     */
    function https_request($url,$json_transfer_back = 1)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        $data = mb_convert_encoding($data, 'utf-8', 'gbk');
        print_r($data);exit();
        if($json_transfer_back == 1){
            $data = json_decode($data, true);
        }

        return $data;
    }


//******************************************grand  cut-off rule*******************************************
#TODO
    /**
     * 导出至excel表格        2017-10-15
     * @param: $fileName表格名字   $headArr表头  $data导出数据  $msg批注
     */
    function getExcel($fileName, $headArr, $data, $msg = '')
    {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            die("data must be a array");
        }

        //检查文件名
        if (empty($fileName)) {
            die("filename must be existed");
        }

        //获取总列数
        $totalColumn = count($headArr);
        $charColumn = chr($totalColumn + 64);
        $date = date("Y-m-d", time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象
        $objPHPExcel = new \PHPExcel();

        $objPHPExcel->setActiveSheetIndex(0);    //设置当前的sheet  操作第一个工作表
        $objActSheet = $objPHPExcel->getActiveSheet();    //添加数据
        $phpstyle = new \PHPExcel_Style_Color();

        //表头变颜色
        $objActSheet->getStyle('A1:' . $charColumn . '1')->getFont()->getColor()->setARGB($phpstyle::COLOR_BLUE);    //设置颜色

        //设置批注
        if (!empty($msg)) {
            $objActSheet->getStyle('A2')->getFont()->getColor()->setARGB($phpstyle::COLOR_RED);
            $objActSheet->setCellValue('A2', $msg);    //给单个单元格设置内容
            $objActSheet->mergeCells('A2:' . $charColumn . '2');    //合并单元格
        }

        //设置表头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objActSheet->setCellValue($colum . '1', $v);
            $objActSheet->getColumnDimension($colum)->setWidth(20);
            $key++;
        }

        //写入数据
        if (!empty($msg)) {
            $column = 3;
        } else {
            $column = 2;
        }
        foreach ($data as $key => $rows) {     //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {    // 列写入
                $j = chr($span);
                if ($keyName !== 'img') {
                    $objActSheet->setCellValue($j . $column, $value);
                } elseif ($keyName == 'img') {
                    $objActSheet->getRowDimension($column)->setRowHeight(60);    //设置行高
                    $objDrawing = new \PHPExcel_Worksheet_Drawing();
                    $objDrawing->setPath($value);
                    $objDrawing->setWidth(50);
                    $objDrawing->setHeight(50);
                    $objDrawing->setCoordinates($j . $column);
                    $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                }
                $span++;
            }
            $column++;
        }

        //处理中文输出问题
        //$fileName = iconv("utf-8", "gb2312", $fileName);

        //接下来当然是下载这个表格了，在浏览器输出就好了
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output'); //文件通过浏览器下载
    }

    /**
     * 获取表格数据   2017-10-15
     * @param: $fileName表格名字   $headArr表头  $data导出数据  $msg批注
     */
    function getData($file_dir)
    {
        $PHPReader = new \PHPExcel_Reader_Excel5();
        if (!$PHPReader->canRead($file_dir)) {
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            if (!$PHPReader->canRead($file_dir)) {
                return array(0, '请上传文档');
            }
        }

        //载入文件
        $PHPExcel = $PHPReader->load($file_dir);

        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet = $PHPExcel->getSheet(0);

        //获取总行数
        $allRow = $currentSheet->getHighestRow();
        $allColumn = $currentSheet->getHighestColumn();
        $allColumn = ord($allColumn);

        for ($j = 2; $j <= $allRow; $j++) {
            for ($i = 65; $i <= $allColumn; $i++) {
                $colum = chr($i);
                $cell = $currentSheet->getCell($colum . $j)->getValue();
                if ($cell instanceof PHPExcel_RichText)     //富文本转换字符串
                {
                    $cell = $cell->__toString();
                }

                $data[$j][$colum] = $cell;
            }
        }
        return array(1, $data);
    }


    /**
     * php完美实现下载远程图片保存到本地   2017-10-15
     * @param: 文件url,保存文件目录,保存文件名称，使用的下载方式    当保存文件名称为空时则使用远程文件原来的名称
     * @date: 2017-05-13
     */
    function getimage($url, $save_dir = '', $filename = '', $type = 0)
    {
        if (trim($url) == '') {
            return array('file_name' => '', 'save_path' => '', 'error' => 1);
        }
        if (trim($save_dir) == '') {
            $save_dir = './';
        }
        if (trim($filename) == '') {//保存文件名
            $ext = strrchr($url, '.');
            if ($ext != '.gif' && $ext != '.jpg') {
                return array('file_name' => '', 'save_path' => '', 'error' => 3);
            }
            $filename = time() . $ext;
        }
        if (0 !== strrpos($save_dir, '/')) {
            $save_dir .= '/';
        }
        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            return array('file_name' => '', 'save_path' => '', 'error' => 5);
        }

        //获取远程文件所采用的方法
        if ($type) {
            $ch = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $img = curl_exec($ch);
            curl_close($ch);

        } else {
            ob_start();
            readfile($url);
            $img = ob_get_contents();
            ob_end_clean();
        }
        //$size=strlen($img);
        //文件大小

        $fp2 = @fopen($save_dir . $filename, 'a');
        fwrite($fp2, $img);
        fclose($fp2);
        unset($img, $url);
        return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
    }

//******************************************项目接口*******************************************
#TODO

    /**
     * 数组 转 对象
     *
     * @param array $arr 数组
     * @return object
     */
    function array_to_object($arr)
    {
        if (gettype($arr) != 'array') {
            return;
        }
        foreach ($arr as $k => $v) {
            if (gettype($v) == 'array' || getType($v) == 'object') {
                $arr[$k] = (object)array_to_object($v);
            }
        }

        return (object)$arr;
    }

    /**
     * 对象 转 数组
     *
     * @param object $obj 对象
     * @return array
     */
    function object_to_array($obj)
    {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)object_to_array($v);
            }
        }

        return $obj;
    }


    /**
     * 创建唯一标示
     * @param int $number 可选位数
     * @return string 最长为88位
     */
    function createUuid($number = 10)
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid = substr($str, 0, floor($number / 5));
        $number -= floor($number / 5);
        $uuid .= substr($str, 8, floor($number / 4));
        $number -= floor($number / 4);
        $uuid .= substr($str, 12, floor($number / 3));
        $number -= floor($number / 3);
        $uuid .= substr($str, 16, floor($number / 2));
        $number -= floor($number / 2);
        $uuid .= substr($str, 20, $number);
        return $uuid;
    }

    /**
     * 加密字符串
     * @param $string
     * @param string $key
     * @return string
     */
    function encryption($string, $key = 'zheshiyigejiamikey')
    {
        $string = urlencode($string);
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
        $nh = rand(0, 64);
        $ch = $chars[$nh];
        $mdKey = md5($key . $ch);
        $mdKey = substr($mdKey, $nh % 8, $nh % 8 + 7);
        $txt = base64_encode($string);
        $tmp = '';
        $i = 0;
        $j = 0;
        $k = 0;
        for ($i = 0; $i < strlen($txt); $i++) {
            $k = $k == strlen($mdKey) ? 0 : $k;
            $j = ($nh + strpos($chars, $txt[$i]) + ord($mdKey[$k++])) % 64;
            $tmp .= $chars[$j];
        }
        return urlencode($ch . $tmp);
    }



    /**
     * 把用户输入的文本转义（主要针对特殊符号和emoji表情）
     * @param string $str
     * @return mixed|string
     */
    function userTextEncode($str)
    {
        if (!is_string($str)) return $str;
        if (!$str || $str == 'undefined') return '';

        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($str) {
            return addslashes($str[0]);
        }, $text); //将emoji的unicode留下，其他不动，这里的正则比原答案增加了d，因为我发现我很多emoji实际上是\ud开头的，反而暂时没发现有\ue开头。
        return json_decode($text);
    }

    /**
     * 解码上面的转义
     * @param string $str
     * @return mixed
     */
    function userTextDecode($str)
    {
        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback('/\\\\\\\\/i', function ($str) {
            return '\\';
        }, $text); //将两条斜杠变成一条，其他不动
        return json_decode($text);
    }

    /**
     * 格式化数字
     * @param string $num 要格式化数字
     * @param int $decimal 保留纪委小数
     * @return string
     */
    function formatNumber($num, $decimal = 2)
    {
        return sprintf('%.' . $decimal . 'f', $num);
    }

    /**
     * array_column() // 不支持低版本;
     * 以下方法兼容PHP低版本
     */
    function _array_column(array $array, $column_key, $index_key=null){
        $result = [];
        foreach($array as $arr) {
            if(!is_array($arr)) continue;

            if(is_null($column_key)){
                $value = $arr;
            }else{
                $value = $arr[$column_key];
            }

            if(!is_null($index_key)){
                $key = $arr[$index_key];
                $result[$key] = $value;
            }else{
                $result[] = $value;
            }
        }
        return $result;
    }

    /**  判断是否是微信浏览器
     * @return bool
     */
    function viaWX()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

}









